<template>
    <div class="app-container">
        <!-- 搜索和操作区域 -->
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="教师姓名">
                <el-input v-model="searchForm.teacherName" placeholder="请输入教师姓名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">查询 <el-icon class="el-icon--right"><Search /></el-icon></el-button>
                <el-button type="success" @click="handleAdd">新增教师 <el-icon class="el-icon--right"><Plus /></el-icon></el-button>
            </el-form-item>
        </el-form>

        <!-- 教师列表 -->
        <el-table v-loading="listLoading" :data="filteredList" element-loading-text="Loading" border fit highlight-current-row>
            <el-table-column align="center" label="ID" width="80px">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="教师编号" prop="teacherNo" align="center">
                <template #default="scope">
                    {{ scope.row.teacherNo }}
                </template>
            </el-table-column>
            <el-table-column label="教师姓名" prop="teacherName" align="center">
                <template #default="scope">
                    <span>{{ scope.row.teacherName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200px">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑 <el-icon class="el-icon--right"><Edit /></el-icon></el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除 <el-icon class="el-icon--right"><Delete /></el-icon></el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/编辑教师对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
            <el-form :model="teacherForm" :rules="rules" ref="formRef" label-width="80px">
                <el-form-item label="教师编号" prop="teacherNo">
                    <el-input v-model="teacherForm.teacherNo" :disabled="isEdit" placeholder="请输入教师编号"></el-input>
                </el-form-item>
                <el-form-item label="教师姓名" prop="teacherName">
                    <el-input v-model="teacherForm.teacherName" placeholder="请输入教师姓名"></el-input>
                </el-form-item>
                <!-- <el-form-item label="职称" prop="title">
                    <el-input v-model="teacherForm.title"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="contact">
                    <el-input v-model="teacherForm.contact"></el-input>
                </el-form-item> -->
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue';
import axios from 'axios'; // 假设您配置了axios实例

const list = ref([]);
const listLoading = ref(true);
// 移除了 currentPage 和 pagesize

const searchForm = ref({
    teacherName: '',
});

const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);
const formRef = ref(null);

const rules = {
    teacherNo: [
        { required: true, message: '请输入教师编号', trigger: 'blur' },
        { min: 1, max: 20, message: '教师编号长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    teacherName: [
        { required: true, message: '请输入教师姓名', trigger: 'blur' },
        { min: 1, max: 50, message: '教师姓名长度在 1 到 50 个字符', trigger: 'blur' }
    ]
};
const teacherForm = ref({
    id: null, // 用于编辑时区分
    teacherNo: '',
    teacherName: '',
});

const filteredList = computed(() => {
    if (!list.value) return [];
    return list.value.filter(item => {
        const nameMatch = searchForm.value.teacherName ? item.teacherName.includes(searchForm.value.teacherName) : true;
        // 可以根据需要添加更多搜索条件
        return nameMatch;
    });
});

// 移除了 paginatedData 计算属性

const getList = async () => {
    listLoading.value = true;
    try {
        // 替换为您的API地址
        const response = await axios.get('/api/teacher/getList',{
          headers: {
            "token": localStorage.getItem("token"),
          },
        });
        list.value = response.data.data || [];
        if (list.value.length === 0) {
            ElMessage.success("暂无教师信息");
        }
    } catch (error) {
        console.error('Failed to fetch list:', error);
        ElMessage.error('获取教师列表失败');
    } finally {
        listLoading.value = false;
    }
};

const handleSearch = () => {
    // currentPage.value = 1; // 搜索后回到第一页 (已移除)
    // getList(); // 如果搜索是后端实现的，则调用getList，否则前端过滤即可
};

const handleAdd = () => {
    isEdit.value = false;
    dialogTitle.value = '新增教师';
    teacherForm.value = {
        id: null,
        teacherNo: '',
        teacherName: '',
    };
    dialogVisible.value = true;
};

const handleEdit = (row) => {
    isEdit.value = true;
    dialogTitle.value = '编辑教师';
    teacherForm.value = { ...row }; // 浅拷贝行数据到表单
    dialogVisible.value = true;
};

const submitForm = async () => {
    try {
        if (isEdit.value) {
            // 替换为您的更新API地址
            await axios.put(`/api/teacher/update/${teacherForm.value.id}`, teacherForm.value, {
                headers: {
                    "token": localStorage.getItem("token"),
                },
            });
            ElMessage.success('更新成功');
        } else {
            // 替换为您的新增API地址
            await axios.post('/api/teacher/add', teacherForm.value, {
                headers: {
                    "token": localStorage.getItem("token"),
                },
            });
            ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
        await getList(); // 重新获取列表
    } catch (error) {
        console.error('Form submission error:', error);
        ElMessage.error(isEdit.value ? '更新失败' : '新增失败');
    }
};

const handleDelete = (row) => {
    ElMessageBox.confirm(`确定删除教师 ${row.teacherName} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            // 替换为您的删除API地址
            await axios.delete(`/api/teacher/delete/${row.id}`, {
                headers: {
                    "token": localStorage.getItem("token"),
                },
            });
            ElMessage.success('删除成功');
            await getList(); // 重新获取列表
        } catch (error) {
            console.error('Delete error:', error);
            ElMessage.error('删除失败');
        }
    }).catch(() => {
        // 用户取消操作
    });
};

// 移除了 handleSizeChange 和 handleCurrentChange 函数

onMounted(() => {
    getList();
});

</script>

<style scoped>
.app-container {
    padding: 20px;
}
.demo-form-inline .el-input {
    width: 180px;
}
.dialog-footer {
    text-align: right;
}
</style>